/************************************************************************
                                                                     
   Xceed Ultimate ListBox for Silverlight                                                                                                                                            
   Copyright (C) 2010 Xceed Software Inc.    
                                                                     
   This program is provided to you under the terms of the GNU General Public  
   License version 2 as published by the Free Software Foundation. 
        
   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY, without even the implied warranty of 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License along 
   with this program, if not, write to the Free Software Foundation, Inc., 
   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

   This program can be provided to you by Xceed Software Inc. under a
   proprietary commercial license agreement for use in non-Open Source
   projects. Visit Xceed.com to find the commercial edition of 
   Xceed Ultimate ListBox for Silverlight.                                    
                                                                      
 **********************************************************************/

using System;

namespace Xceed.Silverlight.Data.Stats
{
  public class VarianceFunction : StatFunction
  {
    public VarianceFunction()
      : base()
    {
    }

    public VarianceFunction( string resultPropertyName, string sourcePropertyName )
      : base( resultPropertyName, sourcePropertyName )
    {
    }

    public VarianceFunction( string resultPropertyName, string sourcePropertyName, bool entirePopulation )
      : base( resultPropertyName, sourcePropertyName )
    {
      m_entirePopulation = entirePopulation;
    }

    #region EntirePopulation Property

    public bool EntirePopulation
    {
      get
      {
        return m_entirePopulation;
      }
      set
      {
        this.CheckSealed();
        m_entirePopulation = value;
      }
    }

    private bool m_entirePopulation = false;

    #endregion

    #region PrerequisiteFunctions Property

    protected internal override StatFunction[] PrerequisiteFunctions
    {
      get
      {
        StatFunction[] prerequisites = m_prerequisites;

        if( prerequisites == null )
        {
          prerequisites = new StatFunction[]
          {
            new AverageFunction( "VarianceFunction.Average", this.SourcePropertyName ),
            new CountFunction( "VarianceFunction.Count", this.SourcePropertyName )
          };

          if( this.IsSealed )
            m_prerequisites = prerequisites;
        }

        return prerequisites;
      }
    }

    #endregion

    protected internal override void InitializeFromInstance( StatFunction source )
    {
      base.InitializeFromInstance( source );

      this.EntirePopulation = ( ( VarianceFunction )source ).EntirePopulation;
    }

    protected internal override void Validate()
    {
      base.Validate();
      this.ValidateSourcePropertyName( 1 );
    }

    protected override void Initialize( Type[] sourcePropertyTypes )
    {
      base.Initialize( sourcePropertyTypes );

      switch( Type.GetTypeCode( sourcePropertyTypes[ 0 ] ) )
      {
        case TypeCode.Char:
        case TypeCode.Byte:
        case TypeCode.SByte:
        case TypeCode.Int16:
        case TypeCode.Int32:
        case TypeCode.Int64:
        case TypeCode.UInt16:
        case TypeCode.UInt32:
        case TypeCode.UInt64:
        case TypeCode.Single:
        case TypeCode.Double:
          m_accumulationType = TypeCode.Double;
          break;

        case TypeCode.Decimal:
          m_accumulationType = TypeCode.Decimal;
          break;
      }
    }

    protected internal override void Reset()
    {
      m_doubleSum = 0d;
      m_decimalSum = 0m;
      m_doubleAverage = 0d;
      m_decimalAverage = 0m;
      m_count = 0;
    }

    protected internal override void InitializePrerequisites( StatResult[] prerequisitesValues )
    {
      if( prerequisitesValues.Length != 2 )
        throw new ArgumentException( "The prerequisite initializers do not match the PrerequisiteFunctions." );

      switch( m_accumulationType )
      {
        case TypeCode.Double:
          m_doubleAverage = Convert.ToDouble( prerequisitesValues[ 0 ].Value );
          break;

        case TypeCode.Decimal:
          m_decimalAverage = Convert.ToDecimal( prerequisitesValues[ 0 ].Value );
          break;
      }

      m_count = Convert.ToInt64( prerequisitesValues[ 1 ].Value );

      if( !m_entirePopulation )
        m_count--;

      if( m_count <= 0 )
      {
        // No need to go further (i.e. Accumulate), the result cannot be calculated.
        throw new DivideByZeroException();
      }
    }

    protected internal override void Accumulate( object[] values )
    {
      if( StatFunction.CanProcessValues( values, 1 ) )
      {
        checked
        {
          switch( m_accumulationType )
          {
            case TypeCode.Double:
              {
                double diff = Convert.ToDouble( values[ 0 ] ) - m_doubleAverage;
                m_doubleSum += diff * diff;
              }
              break;

            case TypeCode.Decimal:
              {
                decimal diff = Convert.ToDecimal( values[ 0 ] ) - m_decimalAverage;
                m_decimalSum += diff * diff;
              }
              break;
          }
        }
      }
    }

    protected internal override StatResult GetResult()
    {
      object result = null;

      switch( m_accumulationType )
      {
        case TypeCode.Double:
          result = m_doubleSum / m_count;
          break;

        case TypeCode.Decimal:
          result = m_decimalSum / m_count;
          break;
      }

      return new StatResult( result );
    }

    protected internal override int GetEquivalenceKey()
    {
      return base.GetEquivalenceKey() ^ this.EntirePopulation.GetHashCode();
    }

    protected internal override bool IsEquivalent( StatFunction statFunction )
    {
      VarianceFunction varianceFunction = statFunction as VarianceFunction;

      if( varianceFunction == null )
        return false;

      if( varianceFunction.EntirePopulation != this.EntirePopulation )
        return false;

      return base.IsEquivalent( statFunction );
    }

    private TypeCode m_accumulationType = TypeCode.Empty;
    private double m_doubleSum;
    private decimal m_decimalSum;
    private double m_doubleAverage;
    private decimal m_decimalAverage;
    private long m_count;
    private StatFunction[] m_prerequisites;
  }
}
